import {
  MessageBox,
  Message
} from 'element-ui'

var baseUrl;
var socket;
export default {
  //连接
  connect(operation) {
    var ip = "127.0.0.1";  
    baseUrl = "ws://" + ip + ":12345";
    this.openSocket(operation);
  },

  //断开
  disconnect() {
    dialog.get_actionType("closeSignal");
    socket.close();
    socket = null;
  },

  openSocket(operation) {
    socket = new WebSocket(baseUrl);
    socket.onclose = function () {
      console.error("web channel closed");
    };
    socket.onerror = function (error) {
      console.error("web channel error: " + error);
      // Message.error("高拍仪连接失败。");
    };
    socket.onopen = function () {
      console.log("WebSocket connected, setting up QWebChannel.");
      new QWebChannel(socket, function (channel) {
        // make dialog object accessible globally
        window.dialog = channel.objects.dialog;
        //网页关闭函数
        window.onunload = function () {
          dialog.get_actionType("closeSignal");
        }
        //关闭/刷新信号
        dialog.send_close.connect(function () {
          console.log("Received message: " + "close!!!");
          window.close();
        });
        dialog.sendPrintInfo.connect(function (message) {
          operation(message);
        });
        //网页加载完成信号
        dialog.html_loaded();
        dialog.get_actionType("startIDCard");
        //dialog.receiveText("Client connected, ready to send/receive messages!");
        console.log("Connected to WebChannel, ready to send/receive messages!");
      });
    }
  }

}
